package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${upload.path}")
    private String pathName;

    //MultipartFile 用于接收二进制文件对象
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取名字
        String originalFilename = file.getOriginalFilename();
        log.info("文件名字:" + originalFilename);
        //最后一次.索引获取
        int lastIndex = originalFilename.lastIndexOf(".");
        log.info("最后一次.的索引" + lastIndex);
        //截取到后缀名
        String fileSuff = originalFilename.substring(lastIndex);
        log.info("截取到的后缀名为:" + fileSuff);
        //UUID随机生成文件名字
        String fileName = UUID.randomUUID().toString() + fileSuff;
        log.info("随机生成的文件名字:" + fileName);

        //判断路径是否存在 不存在 则创建一个
        File dir = new File(pathName);
        if (!dir.exists())
            dir.mkdirs();

        File uploadFile = new File(pathName, fileName);

        try {//写入服务器硬盘中
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("图片上传出现问题请重试");
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.info("获取文件的名称" + name);


        try {
            //获取到服务器硬盘中参数名字的文件
            File file = new File(pathName, name);
            //输入流在服务器硬盘中读取到服务器内存中
            FileInputStream fileInputStream = new FileInputStream(file);
            //获取输出到浏览器的流对象
            ServletOutputStream outputStream = response.getOutputStream();


            int len = 0;
            //相当与一个复制操作 进行回显
            byte[] buffer = new byte[8 * 1024];
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                //读多少写多少
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
